<?php
// +----------------------------------------------------------------------
// | Qbt CMS Plugin
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2018 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 黄老邪 <develop02@qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_order\service;
use cmf\controller\PluginBaseController;
use think\Db;
use think\Config;

class OrderService extends PluginBaseController
{

    public function _initialize()
    {
        $this->config = Config::get('database');
    }   
	/**
	 * 删除订单
	 * 使用方法：
	 *     use plugins\qbt_order\service\OrderService;
	 *     OrderService::del_order($order_id);
	 * @param int $order_id
	 * @return array
	 */
    static public function delOrder($order_id)
    {
        if(Db::name('order_info')->delete($order_id)){
            return ['code' => 0,'msg' => '删除成功'];
        } else {
            return ['code' => -1,'msg' => '请输入合法的order_id'];
        }
    }


    /**
     * 更改订单状态(付款)
     * 使用方法：
     *     use plugins\qbt_order\service\OrderService;
     *     OrderService::pay($order_id);
     * @param int $order_id 订单ID
     * @return array
     */
    static public function pay($order_id)
    {
        if(Db::name('order_info')->where(['order_id' => $order_id])->update(['pay_status' => 2,'pay_time' => time(),'order_status'=>1])){
            return ['code' => 0,'msg' => '付款成功'];
        } else {
            return ['code' => -1,'msg' => '请输入合法的order_id'];
        }
    }   

    /**
     * 更改订单状态(确认收货)
     * 使用方法：
     *     use plugins\qbt_order\service\OrderService;
     *     OrderService::receive($order_id);
     * @param int $order_id 订单ID
     * @return array
     */
    static public function receive($order_id)
    {
        if(Db::name('order_info')->where(['order_id' => $order_id])->update(['shipping_status' => 2])){
            return ['code' => 0,'msg' => '确认收货成功'];
        } else {
            return ['code' => -1,'msg' => '请输入合法的order_id'];
        }
    }  

    /**
     * 更改订单状态(取消订单)
     * 使用方法：
     *     use plugins\qbt_order\service\OrderService;
     *     OrderService::quxiao($order_id);
     * @param int $order_id 订单ID
     * @return array
     */
    static public function quxiao($order_id)
    {
        if(Db::name('order_info')->where(['order_id' => $order_id])->update(['order_status' => 2])){
            return ['code' => 0,'msg' => '取消成功'];
        } else {
            return ['code' => -1,'msg' => '请输入合法的order_id'];
        }
    }            

    /**
     * 更改订单状态(立即发货)
     * 使用方法：
     *     use plugins\qbt_order\service\OrderService;
     *     OrderService::confirmReceipt($order_id,$invoice_no);
     * @param int $order_id 订单ID
     * @param int $invoice_no 发货单号
     * @return array
     */
    static public function confirmReceipt($order_id,$invoice_no)
    {
        if(Db::name('order_info')->where(['order_id' => $order_id])->update(['shipping_status' => 1,'invoice_no' => $invoice_no])){
            return ['code' => 0,'msg' => '发货成功'];
        } else {
            return ['code' => -1,'msg' => '请输入合法的order_id跟发货单号'];
        }
    }

    /**
     * 查看订单详情
     * 使用方法：
     *     use plugins\qbt_order\service\OrderService;
     *     OrderService::detail($order_id);
     * @param int $order_id 订单ID
     * @return array
     */
    static public function detail($order_id)
    {
        $prefix = (new self())->config['prefix'];
        $p_list = Db::query("select * from {$prefix}order_info where order_id=:order_id",['order_id'=>$order_id]);

        $sql = "SELECT o.* ,g.goods_number AS storage FROM {$prefix}order_goods AS o LEFT JOIN {$prefix}goods AS g ON o.goods_id = g.goods_id WHERE o.order_id = {$order_id}";        
        $order_goods = Db::query($sql);
        if(!$order_goods && !$p_list) {
            return ['code' => -1,'msg' => '请输入合法的order_id'];
        }
        return ['code' => 0,'msg' => '获取成功','data' => ['p_list'=>$p_list, 'order_goods' => $order_goods]];
    }

    /**
     * 获取订单列表
     * 使用方法：
     *     use plugins\qbt_order\service\OrderService;
     *     OrderService::orderList($where);
     * @param array $where
     * @return array
     */
    static public function orderList($where = "")
    {
        $p_list = Db::name('order_info')
            ->where($where)
            ->field('order_id,order_sn,add_time,consignee,goods_amount,order_amount,order_status,pay_status,shipping_status,tel,address')
            ->paginate(10);
        return $p_list;
    } 

    /**
     * 创建一个订单
     * 使用方法：
     *     use plugins\qbt_order\service\OrderService;
     *     OrderService::createOrder($cart_id,$cart_num_str,$address_id,$user_id);
     * @param int $cart_id 购物车ID
     * @param string $cart_num_str 购物车商品数量(用逗号分割的字符串)
     * @param int 收货地址 ID
     * @param int $user_id 用户ID  
     * @return array
     */
    static public function createOrder($cart_id,$cart_num_str,$address_id,$user_id)
    {
        $prefix = (new self())->config['prefix'];
        // 根据用户ID获取oppenid
        $openid      = DB::name('user')->where(['id' => $user_id])->value('openid'); 
        $cart_num     = explode(',', $cart_num_str);
        $sql   = "SELECT g.goods_img,g.goods_id,g.goods_name,g.goods_sn,g.shop_price,c.store_name,g.market_price,g.is_real FROM {$prefix}cart c RIGHT JOIN {$prefix}goods g ON c.goods_id = g.goods_id WHERE c.cart_id IN ({$cart_id}) AND c.buyer_id = {$user_id}";
        $goods = Db::query($sql); // 准备商品数据
        if(!$goods) return ['code' => -1,'msg' => '缺少相应的参数'];
        $count = count($cart_num);
        $total = '';
        for( $i=0; $i<$count; $i++ ){
            $total += $goods[$i]['shop_price'] * 100  * $cart_num[$i]; // 算出商品总价格
        }
        $total /= 100;
        //得到收获地址信息
        $address = DB::name('address')->where(['address_id' => $address_id])->find();

        // 准备订单数据 
        $order_data = [
            'user_id'         => $user_id,
            'consignee'       => $address['true_name'],
            'province'        => $address['county'],
            'city'            => $address['city'],
            'district'        => $address['area_info'],
            'address'         => $address['address'],
            'tel'             => $address['mob_phone'],
            'goods_amount'    => $total,
            'order_amount'    => $total,
            'add_time'        => time(),
        ];
        // 创建一个新的订单
        $order_id = Db::name('order_info')->insertGetId($order_data);
        if($order_id){
            return ['code' => 0,'msg' => '成功创建订单','data' => ['order_id' => $order_id,'open_id'=>$openid,'count' => $count,'goods' => $goods]];
        } else {
            return ['code' => -1,'msg' => '请输入合法的参数'];
        }

    }       

}
